import com.lq.ecoldchain.config.AppConfig
import com.lq.ecoldchain.internet.APIService
import com.lq.ecoldchain.internet.TokenInterceptor
import com.lq.ecoldchain.internet.WChatAPIService
import com.lq.ecoldchain.model.WeChatModel
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object BaseNetCore {
    val ApiServiceImpl by lazy { createAPI() }
    val WeChatApiImpl by lazy { createWxAPI() }
    private fun <T> create(clazz: Class<T>): T = retrofit.create(clazz)

    private fun <T> createWx(clazz:Class<T>):T = wxRetrofit.create(clazz)

    private lateinit var okHttpClient: OkHttpClient

     fun initRetrofit() {
        val httpLogger = HttpLoggingInterceptor()
        httpLogger.level = HttpLoggingInterceptor.Level.BODY
        okHttpClient = OkHttpClient.Builder()
                .addInterceptor(httpLogger)
                .addInterceptor(TokenInterceptor())
                .addInterceptor(ResultCheckInterceptor())
                .connectTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .build()
    }

    private val retrofit by lazy {
        Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build()
    }

    private val wxRetrofit by lazy {
        val httpLogger = HttpLoggingInterceptor()
        httpLogger.level = HttpLoggingInterceptor.Level.BODY
       val client = OkHttpClient.Builder()
                .addInterceptor(httpLogger)
                .connectTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .build()
        Retrofit.Builder()
                .baseUrl(WeChatModel.baseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build()
    }



    private fun createAPI(): APIService {
        return BaseNetCore.create(APIService::class.java)
    }

    private fun createWxAPI():WChatAPIService{
        return BaseNetCore.createWx(WChatAPIService::class.java)
    }


}